package com.chujian.file.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import com.chujian.file.service.IOssService;
import com.chujian.framework.core.base.TsDataController;
import com.chujian.framework.core.tsdata.Result;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author ：chujian
 * @date ：2020-12-09
 * 通用对象存储控制器
 */
@RestController
@AllArgsConstructor
@Slf4j
public class OssController extends TsDataController {
    private final IOssService ossService;

    /**
     * 通用文件上传
     *
     * @param bucket  存储桶
     * @param path    路径
     * @param request
     * @return
     */
    @PostMapping("/oss/upload")
    public Result upload(
            @RequestParam(value = "bucket", required = false) String bucket,
            @RequestParam("path") String path,
            HttpServletRequest request
    ) {
        return uploadOss(bucket, path, request);
    }

    private Result uploadOss(String bucket, String path, HttpServletRequest request) {
        List<String> urls = new ArrayList<>();
        try {
            StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
            Iterator<String> iterator = req.getFileNames();
            while (iterator.hasNext()) {
                MultipartFile file = req.getFile(iterator.next());
                // 获取文件名
                assert file != null;
                String fileName = file.getOriginalFilename();
                String objectName = path + "/" + IdUtil.simpleUUID() + "." + FileUtil.getSuffix(fileName);
                String url = ossService.fileUpload(bucket, objectName, file);
                urls.add(url);
                log.info(" 文件:" + fileName + " 上传成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return errRs("上传失败");

        }
        return okRs(CollUtil.join(urls, ","));
    }

    /**
     * 下载
     *
     * @param bucket
     * @param objectName
     * @param response
     * @throws IOException
     */
    @GetMapping("/oss/download")
    public void getObject(
            @RequestParam("bucket") String bucket,
            @RequestParam("objectName") String objectName,
            HttpServletResponse response) throws IOException {
        doDownload(bucket, objectName, response);
    }


    /**
     * 开放下载
     *
     * @param bucket
     * @param objectName
     * @param response
     * @throws IOException
     */
    @GetMapping("/open/oss/download")
    public void getOpenObject(
            @RequestParam("bucket") String bucket,
            @RequestParam("objectName") String objectName,
            HttpServletResponse response) throws IOException {
        doDownload(bucket, objectName, response);
    }

    public void doDownload(String bucket, String objectName, HttpServletResponse response) throws IOException {

        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);

        String suffix = objectName.substring(objectName.lastIndexOf(".") + 1);
        if (suffix.equals("doc") || suffix.equals("docx")) {
            response.setContentType("application/msword");
        } else if (suffix.equals("pdf")) {
            response.setContentType("application/pdf");
        } else {
            response.setContentType("image/jpeg");
        }

        String fileName = objectName.replace("/", "-");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        InputStream inputStream = ossService.getObject(bucket, objectName);
        IoUtil.copy(inputStream, response.getOutputStream());
    }


}
